<template>
  <div class="product-detail">
    <!-- 面包屑导航 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Basiclist' }">基本信息</el-breadcrumb-item>
      <el-breadcrumb-item>产品详情</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 顶部操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="modifyBasicInfo">修改基本信息</el-button>
      <el-button type="success" @click="exportTraceCode">导出溯源码</el-button>
    </div>

    <!-- 产品基本信息 -->
    <el-card class="product-info-card">
      <div class="product-info">
        <div class="product-image">
          <img :src="productInfo.picture" alt="产品图片" />
          <div class="product-logo">爱吃兔</div>
        </div>
        <div class="product-details">
          <h2>{{ productInfo.storeName }}</h2>
          <div class="product-attributes">
            <div class="attribute-row">
              <span>生产批次: {{ productInfo.batch }}</span>
              <span>保质期: {{ productInfo.expiration }}天</span>
            </div>
            <div class="attribute-row">
              <span>生产许可证号: {{ productInfo.license }}</span>
              <span>生产企业: {{ productInfo.company }}</span>
            </div>
          </div>
          <div class="inspection-reports">
            <h3>产品检验报告</h3>
            <div class="report-uploads">
              <div class="uploaded-reports">
                <div
                  v-for="(img, idx) in reportList"
                  :key="img.id"
                  class="report-img-wrapper"
                >
                  <img v-if="img.imagePath" :src="img.imagePath" class="report-img" />
                  <el-icon class="img-delete-x" @click="deleteImage(img.id)">
                    <Close />
                  </el-icon>
                </div>
                <!-- 上传按钮，最多9张 -->
                <label v-if="reportList.length < 10" class="report-upload">
                  <input
                    type="file"
                    accept="image/*"
                    name="ImageFile"
                    style="display: none"
                    @change="handleReportUpload"
                  />
                  <el-icon class="plus-icon"><Plus /></el-icon>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="traceability-tabs">
      <el-tab-pane label="养殖信息" name="breeding">
        <BreedingInfo :batch="productInfo.batch" />
      </el-tab-pane>
      <el-tab-pane label="屠宰信息" name="slaughter">
        <SlaughterInfo :batch="productInfo.batch" />
      </el-tab-pane>
      <el-tab-pane label="深加工信息" name="processing">
        <ProcessingInfo :batch="productInfo.batch" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ArrowRight, Plus, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BreedingInfo from './components/BreedingInfo.vue'
import SlaughterInfo from './components/SlaughterInfo.vue'
import ProcessingInfo from './components/ProcessingInfo.vue'
import { Traceability } from '@/Utils/Http' 

const route = useRoute()
const activeTab = ref('breeding')


// 产品基本信息
const productInfo = reactive({
  id: 0,
  storeName: '兔头 (麻辣味)',
  batch: '20210718',
  expiration: 90,
  license: 'SC213205427680',
  company: '成都爱吃兔食品加工有限公司',
  picture: '/src/assets/log/AAA.png'
})

// 产品检验报告图片列表
const reportList = ref<any[]>([])

// 文件上传相关
const fileInputRef = ref<HTMLInputElement>()

// 修改基本信息
const modifyBasicInfo = () => {
  ElMessage.primary('修改信息功能请前往基本信息页面,!!!请稍等!!!')
  setTimeout(() => {
      location.href='/basiclist'
    }, 2000);
}

// 导出溯源码
const exportTraceCode = () => {
  ElMessage.info('导出溯源码功能请前往基本信息页面,!!!请稍等!!!')
  setTimeout(() => {
      location.href='/basiclist'
    }, 2000);
}

// 显示产品检验报告的图片 固定类型为1
async function fetchReportImages() {
  const batch = route.query.batch;
  try {
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: {
        BatchNo: batch,
        ImageType: '1'
      }
    });
    // 根据API文档，数据结构为 { id, imagePath }
    reportList.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item:any) => !!item && !!item.imagePath)
      : [];
  } catch (error) {
    console.error('获取检验报告图片失败:', error);
    ElMessage.error('获取检验报告图片失败');
  }
}

// 上传产品检验报告的图片
async function handleReportUpload(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (!files || !files.length) return
  if (reportList.value.length + files.length > 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }
 
  const formData = new FormData()
  //  修改字段名为 ImageFile，与后端一致
  formData.append('ImageFile', files[0])
  //  添加批次号和图片类型到FormData中
  formData.append('BatchNo', route.query.batch as string)
  formData.append('ImageType', '1')
 
  try {
    const res = await Traceability.post('/UploadBatchImage/UploadBatch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
 
    // 检查响应状态
    if (res.data && res.data.code === 300) {
      ElMessage.success('产品检验报告上传成功')
      // 上传成功后重新获取图片列表
      await fetchReportImages()
    } else {
      ElMessage.error(res.data?.message || '上传失败')
    }
  } catch (err) {
    console.error('上传失败:', err)
    ElMessage.error('上传失败')
  }
  
  // 清空文件输入，允许重复选择相同文件
  (event.target as HTMLInputElement).value = ''
}

// 删除产品检验报告的图片
async function deleteImage(id: string) {
  try {
    await ElMessageBox.confirm('确定删除产品检验报告图片么?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await Traceability.delete('/UploadBatchImage/DelBatchImage', {
      params: {
        Id: id,
        ImageType: '1'
      }
    });
    
    // 检查响应状态
    if (res.data && res.data.code === 500) {
      ElMessage.success('产品检验报告删除成功');
      // 删除成功后刷新图片列表
      await fetchReportImages();
    } else {
      ElMessage.error(res.data?.message || '删除失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    console.error('删除图片失败:', error);
    ElMessage.error('删除失败');
  }
}

onMounted(() => {
  // 根据路由参数获取产品信息
  const batch = route.query.batch as string
  if (batch) {
    productInfo.batch = batch
    // 这里应该调用API获取产品详情
    loadProductDetail(batch)
    // 获取产品检验报告图片
    fetchReportImages()
  }
})

// 加载产品详情
const loadProductDetail = (batch: string) => {
  // 预留接口调用
  console.log('加载产品详情，批次号：', batch)
  // 实际项目中应该调用API
  Traceability.get(`/Basic/GetFanBasicQuery?Batch=`+batch).then(res => {
    Object.assign(productInfo, res.data.data)
  })
}



</script>

<style scoped>
.product-detail {
  padding: 20px;
}

.action-bar {
  margin: 20px 0;
  text-align: right;
}

.product-info-card {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  gap: 20px;
}

.product-image {
  position: relative;
  width: 200px;
  height: 200px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-logo {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-details {
  flex: 1;
}

.product-details h2 {
  margin: 0 0 20px 0;
  color: #333;
}

.product-attributes {
  margin-bottom: 20px;
}

.attribute-row {
  display: flex;
  gap: 40px;
  margin-bottom: 10px;
}

.attribute-row span {
  color: #666;
}

.inspection-reports h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.report-uploads {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.uploaded-reports {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.report-img-wrapper {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.report-img-wrapper:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
}

.report-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.img-delete-x {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(245, 108, 108, 0.9);
  color: white;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.img-delete-x:hover {
  background: #f56c6c;
  transform: scale(1.1);
}

.report-upload {
  width: 80px;
  height: 80px;
  border: 2px dashed #ddd;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s ease;
  background: #fafafa;
}

.report-upload:hover {
  border-color: #409eff;
  color: #409eff;
  background: #f0f9ff;
  transform: translateY(-2px);
}

.plus-icon {
  font-size: 24px;
}

.traceability-tabs {
  margin-top: 20px;
}
</style>
